/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var convertBST = function (root) {
  //记录逆序遍历节点值，初始化为0
  let tempval = 0

  function dfs(node) {
    //如果节点为空，直接返回
    if (!node) return

    /* 按照逆中序遍历（右、根、左）的顺序遍历搜索树 */
    if (node.right) dfs(node.right)
    node.val += tempval
    tempval = node.val
    if (node.left) dfs(node.left)
  }
  dfs(root)
  return root
}